package com.py.framework.core.ds;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 动态数据源切入点
 * @author Leegern
 * @date 2016年9月6日
 */
@Aspect
@Order(-1)  // 保证该AOP在@Transactional之前执行
@Component
public class DataSourceAspect {
	

	@Before("@annotation(ds)")
	public void changeDataSource(JoinPoint point, DynamicDataSource ds) throws Throwable {
		// 获取设置的数据源
		String dbType = ds.value().getValue();
		if (StringUtils.isBlank(dbType)) {
			throw new RuntimeException("The current DynamicDataSource is not found!");
		}
		// 设置切换数据源
		DataSourceContextHolder.setDbType(dbType);
	}

	@After("@annotation(ds)")
	public void resetDataSource(JoinPoint point, DynamicDataSource ds) {
		DataSourceContextHolder.clearDbType();
	}
	
}